using System;
using System.Collections.Generic;
using System.Linq.Expressions;

public interface IRepository<T> where T : class
{
    // 查询方法
    IEnumerable<T> Query(Expression<Func<T, bool>> whereExp = null);
    T Get(Expression<Func<T, bool>> whereExp);
    bool Exists(Expression<Func<T, bool>> whereExp);
    int Count(Expression<Func<T, bool>> whereExp = null);
    
    // 分页查询
    (IEnumerable<T> Data, int Total) QueryPaged(Expression<Func<T, bool>> whereExp, int pageIndex, int pageSize);
    
    // 创建查询构建器
    IQueryBuilder<T> CreateQueryBuilder(Expression<Func<T, bool>> whereExp = null);
}

public class Repository<T> : IRepository<T> where T : class
{
    private readonly IDbConnection _connection;
    
    public Repository(IDbConnection connection)
    {
        _connection = connection;
    }
    
    public IEnumerable<T> Query(Expression<Func<T, bool>> whereExp = null)
    {
        var builder = CreateQueryBuilder(whereExp);
        return _connection.Query(builder);
    }
    
    public T Get(Expression<Func<T, bool>> whereExp)
    {
        var builder = CreateQueryBuilder(whereExp);
        return _connection.QuerySingle(builder);
    }
    
    public bool Exists(Expression<Func<T, bool>> whereExp)
    {
        var builder = CreateQueryBuilder(whereExp);
        return _connection.Exists(builder);
    }
    
    public int Count(Expression<Func<T, bool>> whereExp = null)
    {
        var builder = CreateQueryBuilder(whereExp);
        return _connection.Count(builder);
    }
    
    public (IEnumerable<T> Data, int Total) QueryPaged(Expression<Func<T, bool>> whereExp, int pageIndex, int pageSize)
    {
        var builder = CreateQueryBuilder(whereExp);
        return _connection.QueryPaged(builder, pageIndex, pageSize);
    }
    
    public IQueryBuilder<T> CreateQueryBuilder(Expression<Func<T, bool>> whereExp = null)
    {
        return _connection.CreateQueryBuilder(whereExp);
    }
}